const InstanceList = {};

class Progress {
    constructor(template) {
        this.progressNow = 0;
        this.progressAll = 0;
        this.progressTemplate = ""
    }

    setTemplate(template) {
        this.progressTemplate = template;
    }

    addAll(num, notPrint) {
        this.progressAll += num;
        if (!notPrint) {
            this.print();
        }
    }

    addNow(num, notPrint) {
        this.progressNow += num;
        if (!notPrint) {
            this.print();
        }
    }

    setAll(num, notPrint) {
        this.progressAll = num;
        if (!notPrint) {
            this.print();
        }
    }

    setNow(num, notPrint) {
        this.progressNow = num;
        if (!notPrint) {
            this.print();
        }
    }

    print() {
        let text = `${this.progressNow} / ${this.progressAll} `;
        if (this.progressTemplate) {
            text = this.progressTemplate;
            text = text.replace('[all]', this.progressAll)
            text = text.replace('[now]', this.progressNow)
        }
        if (this.progressNow === this.progressAll) {
            process.stdout.write(`${text} \n`)
        } else {
            process.stdout.write(`${text} \r`)
        }

    }

    reset() {
        this.progressAll = 0;
        this.progressNow = 0
    }
}

module.exports = {
    /**
     *
     * @param key
     * @returns {Progress}
     */
    getInstance(key) {
        if (InstanceList[key]) {
            return InstanceList[key]
        }
        InstanceList[key] = new Progress();
        return InstanceList[key];
    }
}
